# 第二课堂管理系统菜单结构修复和启动脚本
# 此脚本将调整菜单结构并启动系统

Write-Host "===== 第二课堂管理系统菜单结构修复和启动脚本 =====" -ForegroundColor Green
Write-Host "此脚本将调整菜单结构并启动系统" -ForegroundColor Green

# 设置数据库连接参数
$DB_USER = "root"
$DB_PASSWORD = "123456"
$DB_NAME = "scms"
$DB_HOST = "localhost"
$DB_PORT = "3306"

Write-Host "数据库连接信息:" -ForegroundColor Cyan
Write-Host "用户名: $DB_USER" -ForegroundColor Cyan
Write-Host "数据库: $DB_NAME" -ForegroundColor Cyan
Write-Host "主机: $DB_HOST:$DB_PORT" -ForegroundColor Cyan
Write-Host ""

# 步骤1: 检查并停止已运行的实例
Write-Host "步骤1: 检查并停止已运行的实例..." -ForegroundColor Yellow
$processes = Get-NetTCPConnection -LocalPort 8089 -ErrorAction SilentlyContinue | Select-Object OwningProcess
foreach ($process in $processes) {
    $id = $process.OwningProcess
    Write-Host "发现端口8089被进程PID: $id占用，尝试终止..." -ForegroundColor Red
    Stop-Process -Id $id -Force
}

# 步骤2: 执行菜单结构修复SQL
Write-Host "步骤2: 执行菜单结构修复SQL..." -ForegroundColor Yellow
try {
    # 检查mysql命令是否可用
    if (Get-Command mysql -ErrorAction SilentlyContinue) {
        # 使用命令行执行SQL脚本
        mysql -u $DB_USER -p$DB_PASSWORD -h $DB_HOST -P $DB_PORT $DB_NAME < "sql/menu_restructure.sql"
        if ($LASTEXITCODE -ne 0) {
            Write-Host "错误: 执行SQL脚本失败，请检查数据库连接参数。" -ForegroundColor Red
            exit 1
        } else {
            Write-Host "SQL脚本执行成功！" -ForegroundColor Green
        }
    } else {
        Write-Host "警告: 未找到mysql命令，请手动执行sql/menu_restructure.sql脚本。" -ForegroundColor Yellow
    }
} catch {
    Write-Host "错误: 执行SQL脚本时出错 - $_" -ForegroundColor Red
    exit 1
}

# 步骤3: 修复Mapper和Domain问题
Write-Host "步骤3: 修复Mapper和Domain问题..." -ForegroundColor Yellow
if (Test-Path "fix_mapper_issues_enhanced.bat") {
    cmd /c fix_mapper_issues_enhanced.bat
    if ($LASTEXITCODE -ne 0) {
        Write-Host "错误: 修复Mapper和Domain问题失败。" -ForegroundColor Red
        exit 1
    } else {
        Write-Host "Mapper和Domain问题修复成功！" -ForegroundColor Green
    }
} else {
    Write-Host "未找到fix_mapper_issues_enhanced.bat，跳过Mapper和Domain问题修复。" -ForegroundColor Yellow
}

# 步骤4: 启动系统
Write-Host "步骤4: 启动系统..." -ForegroundColor Yellow
Set-Location scms-admin
mvn spring-boot:run

Write-Host "===== 菜单结构修复完成！=====" -ForegroundColor Green
Write-Host "系统已启动，请刷新浏览器查看修改后的菜单结构。" -ForegroundColor Green

Read-Host "按Enter键继续" 